<?php

namespace app\controller\api;

use app\core\ApiController;
use app\core\Request;
use app\core\util\Encryp;
use app\model\LotusLamp;
use app\service\LotusLampService;
use app\service\OrderService;
use app\service\TempleService;

class Temple extends ApiController
{
    public function login()
    {
        $account = input('post.account');
        $password = input('post.password');
        $templeService = TempleService::invoke();
        $token = $templeService->login($account, $password);
        $this->response->success(['token' => $token], "登录成功");
    }

    /**
     * 获取个人主页数据
     */
    public function home()
    {
        $start_time = input('get.start_time');
        $end_time = input('get.end_time');
        $temple_id = Request::invoke()->getTemple('temple_id');
        $TempleInfo = Request::invoke()->getTemple();
        $home = [
            'sum_amount' => isset($TempleInfo['sum_amount']) ? $TempleInfo['sum_amount'] : '0.00',
            'you_sum_amount' => isset($TempleInfo['you_sum_amount']) ? $TempleInfo['you_sum_amount'] : '0.00',
            'user_num' => isset($TempleInfo['user_num']) ? $TempleInfo['user_num'] : 0,
            'deng_num' => isset($TempleInfo['deng_num']) ? $TempleInfo['deng_num'] : 0,
            'a_amount' => isset($TempleInfo['a_amount']) ? $TempleInfo['a_amount'] : '0.00',
            'b_amount' => isset($TempleInfo['b_amount']) ? $TempleInfo['b_amount'] : '0.00',
            'c_amount' => isset($TempleInfo['c_amount']) ? $TempleInfo['c_amount'] : '0.00',
            'd_amount' => isset($TempleInfo['d_amount']) ? $TempleInfo['d_amount'] : '0.00',
            'deng_amount' => isset($TempleInfo['deng_amount']) ? $TempleInfo['deng_amount'] : '0.00',
            'you_amount' => isset($TempleInfo['you_amount']) ? $TempleInfo['you_amount'] : '0.00',
        ];
        $member = [
            'amount' => isset($TempleInfo['amount']) ? $TempleInfo['amount'] : '0.00',
            'pay_amount' => isset($TempleInfo['pay_amount']) ? $TempleInfo['pay_amount'] : '0.00',
            'unset_amount' => isset($TempleInfo['unset_amount']) ? $TempleInfo['unset_amount'] : '0.00',
            'name' => $TempleInfo['name'],
            'temple_id' => $TempleInfo['temple_id'],
            'address' => $TempleInfo['address'],
            'account' => $TempleInfo['account'],
            'avatar' => 'http://pray.veac.cn/storage/avatar.png'
        ];
        $data = [
            'home' => $home,
            'member' => $member,

        ];
        $this->response->success($data);
    }


    /**
     * 获取寺庙的列表
     */
    public function list()
    {
        $page = input('post.page', 1);
        $limit = input('post.limit', 10);
        $searchQuery = input('post.', []);
        $list = TempleService::invoke()->getList($page, $limit, $searchQuery);
        $this->response->success($list);
    }

    /**
     * 获取寺庙的详情
     */
    public function info()
    {
        $id = input('get.id');
        $info = TempleService::invoke()->info($id);
        $this->response->success($info);
    }

    /**
     * 获取寺庙的莲花灯列表
     */
    public function getLampList()
    {
        $id = input('post.id');
        $page = input('post.page', 1);
        $limit = input('post.limit', 10);
        $searchQuery = input('post.', []);
        $searchQuery['temple_id'] = $id;
        $info = LotusLampService::invoke()->getList($page, $limit, $searchQuery);
        $this->response->success($info);
    }

    /**
     * 定时任务-获取所有寺庙列表接口
     */
    public function projectsList()
    {
        $url = 'http://device.api.fjxmlz.com:18081/api/projects';
        $header = [
            'Content-Type: application/json'
        ];
        $params = '';
        $result = $this->request_post($url, $header, $params);
        $result = json_decode($result, true);
        if (!empty($result['data'])) {
            foreach ($result['data'] as $value) {
                $info = (new \app\model\Temple())->where('temple_id', '=', $value['id'])->find();
                if (!empty($info)) {
                    $info->save(
                        [
                            'temple_id' => $value['id'],
                            'name' => $value['name'],
                            'alias' => $value['alias'],
                            'pno' => $value['pno'],
                            'adcode' => $value['adcode'],
                            'province' => $value['province'],
                            'city' => $value['city'],
                            'area' => $value['area'],
                            'address' => $value['address'],
                            'passwords' => Encryp::password(123456),
                            'update_time' => date('Y-m-d H:i:s', time())
                        ]
                    );
                } else {
                    $saveData = [
                        'temple_id' => $value['id'],
                        'name' => $value['name'],
                        'alias' => $value['alias'],
                        'pno' => $value['pno'],
                        'adcode' => $value['adcode'],
                        'province' => $value['province'],
                        'city' => $value['city'],
                        'area' => $value['area'],
                        'address' => $value['address'],
//                        'account' => substr(time(), 0, 8) . rand(100, 999),
                        'create_time' => date('Y-m-d H:i:s', time()),
                        'update_time' => date('Y-m-d H:i:s', time())
                    ];
                    (new \app\model\Temple())->create($saveData);
                }
            }
        }
        $this->response->success($result);
    }

    /**
     * 定时任务-获取第三方设备列表接口
     */
    public function devicesList()
    {
        $projectId = input('get.project_id', '');
        $url = 'http://device.api.fjxmlz.com:18081/api/devices';
        $params = [];
        if ($projectId) {
            $params['projectId'] = $projectId;
        }
        $header = [
            'Content-Type: application/json'
        ];
        $params = $params ? json_encode($params) : '{}';
        $result = $this->request_post($url, $header, $params);
        $result = json_decode($result, true);
        if (!empty($result['data'])) {
            foreach ($result['data'] as $value) {
                if (empty($value['projectId'])) {
                    continue;
                }
                $info = LotusLamp::where('device_no', $value['sn'])->find();
                if (!empty($info)) {
                    $info->save(
                        [
                            'temple_name' => isset($value['projectName']) ? $value['projectName'] : '',
                            'temple_id' => isset($value['projectId']) ? $value['projectId'] : 0,
                            'pno' => $value['pno'],
                            'device_no' => $value['sn'] ?? null,
                            'lamp_device_no' => $value['ccid'] ?? null,
                            'monitor_device_no' => $value['imei'] ?? null,
                            'ccid' => $value['ccid'] ?? null,
                            'imei' => $value['imei'] ?? null,
                            'create_time' => date('Y-m-d H:i:s', time()),
                            'update_time' => date('Y-m-d H:i:s', time())
                        ]
                    );
                } else {
                    $saveData = [
                        'temple_name' => isset($value['projectName']) ? $value['projectName'] : '',
                        'temple_id' => isset($value['projectId']) ? $value['projectId'] : 0,
                        'pno' => $value['pno'],
                        'device_no' => $value['sn'] ?? null,
                        'lamp_device_no' => $value['ccid'] ?? null,
                        'monitor_device_no' => $value['imei'] ?? null,
                        'ccid' => $value['ccid'] ?? null,
                        'imei' => $value['imei'] ?? null,
                        'create_time' => date('Y-m-d H:i:s', time()),
                        'update_time' => date('Y-m-d H:i:s', time()),
                    ];
                    (new LotusLamp())->create($saveData);
                }

            }
        }
        $this->saveRodNum();
        $this->response->success($result);
    }

    public function saveRodNum()
    {
        $LotusLampList = LotusLamp::where(['is_delete' => 0])->select()->toArray();
        $temple_ids = array_unique(array_column($LotusLampList, 'temple_id'));
        foreach ($temple_ids as $temple_id) {
            $list = LotusLamp::where(['temple_id' => $temple_id, 'is_delete' => 0])->select()->toArray();
            $num = count($list);
            for ($i = 0; $i < $num; $i++) {
                $info = LotusLamp::where(['id' => $list[$i]['id']])->find();
                $info->save(['rod_num' => $i + 1]);
            }
        }
    }

    public function request_post($url = '', $header = array(), $data_string = '')
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        } else {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($data_string))
            );
        }
        $result = curl_exec($ch);
        return $result;
    }

}